package com.youxue.teachin.common.upload;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 在此写用途
 *
 * @author: zhiwei
 * @date: 2017-10-07 23:23
 * @version: 9.1.0
 */
public class UploadManager {
    private static UploadManager sUploadManager;
    UploadUserCase mUploadUserCase = new UploadUserCase();

    private String defaultSuffix = "jpg";

    private String getSuffix(String filePath) {
        int index = filePath.lastIndexOf(".");
        if (index > 0) {
            return filePath.substring(index);
        }

        return defaultSuffix;
    }

    /**
     * 值上传1张
     * @param filePath
     * @return
     */
    public Observable<String> uploadImageRX(final String filePath) {
        return mUploadUserCase.getUploadUrl("001", getSuffix(filePath))
            .flatMap(new Func1<UploadVO, Observable<String>>() {
                @Override
                public Observable<String> call(final UploadVO uploadVO) {
                    if (uploadVO == null) {
                        return Observable.error(new UploadExeption("获取上传地址失败"));
                    }
                    return uploadImageRX(filePath, uploadVO.uploadUrl)
                        .flatMap(new Func1<Boolean, Observable<String>>() {
                            @Override
                            public Observable<String> call(Boolean aBoolean) {
                                if (!aBoolean) {
                                    Observable.error(new UploadExeption("上传失败"));
                                }
                                return Observable.just(uploadVO.callUrl);
                            }
                        });

                }
            }).subscribeOn(Schedulers.io());
    }

    /**
     * @param filePath      本地文件
     * @param tempUploadUri 上传地址
     * @return
     */
    private Observable<Boolean> uploadImageRX(final String filePath, final String tempUploadUri) {
        return Observable.create(new OnSubscribe<Boolean>() {
            @Override
            public void call(Subscriber<? super Boolean> subscriber) {
                try {
                    int response = uploadImage(filePath, tempUploadUri);
                    if (response == 200) {
                        subscriber.onNext(true);
                        subscriber.onCompleted();
                    } else {
                        subscriber.onNext(false);
                        subscriber.onCompleted();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    subscriber.onError(e);
                }
            }
        });
    }

    /**
     * 上传图片
     *
     * @param filePath      图片本地地址
     * @param tempUploadUri 服务器上传零时接口。
     */
    public int uploadImage(String filePath, String tempUploadUri) throws IOException {
        return uploadFile(tempUploadUri, filePath, "image/"+getSuffix(filePath));
    }

    public int uploadFile(String uploadUri, String file, String contentType) throws IOException {
        BufferedReader bufferedReader = null;
        try {
            URL url = new URL(uploadUri);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream input = new FileInputStream(file);
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestMethod("PUT");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream outputStream = conn.getOutputStream();
            byte[] bs = new byte[1024];
            int length = 0;
            while((length = input.read(bs, 0, 1024))!=-1){
                outputStream.write(bs, 0,length);
            }
            outputStream.flush();
            outputStream.close();

            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";
            String result = "";
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            System.out.println("conn.getResponseCode():"+conn.getResponseCode());
            System.out.println(result);
            //bufferedReader.close();
            return conn.getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }
    }

    public static UploadManager getInstance() {
        if (sUploadManager == null) {
            sUploadManager = new UploadManager();

        }
        return sUploadManager;
    }

    private UploadManager() {
    }
}
